package org.jeecg.common.util;

import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 
 * 类描述：java对象序列化及反序列化定义类
 * 
 * @author: liupan
 * @version 1.0
 */

@Component
public class SerializeUtils {

	/***
	 * 将对象序列化为字符数组
	 * @param obj
	 * @return
	 */
	public byte[] serializeObject(Object obj) {
		ByteArrayOutputStream byteOutputStream = null;
		ObjectOutputStream objectOutputStream = null;

		try{
			byteOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteOutputStream);

			objectOutputStream.writeObject(obj);
			objectOutputStream.flush();

			return byteOutputStream.toByteArray();
		}catch(Exception e){
			e.printStackTrace();
		} finally {
			if(null != objectOutputStream){
				try{
					objectOutputStream.close();
					byteOutputStream.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	/***
	 * 将字符数组反序列化为对象
	 * @param bytes
	 * @return
	 */
	public Object deserializeObject(byte[] bytes) {
		ByteArrayInputStream byteInputStream = null;
		ObjectInputStream objectInputStream = null;

		try{
			byteInputStream = new ByteArrayInputStream(bytes);
			objectInputStream = new ObjectInputStream(byteInputStream);

			return objectInputStream.readObject();

		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(null != objectInputStream){
				try{
					objectInputStream.close();
					byteInputStream.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}